import FormValidateMessage from '@/components/Common/Validate/ValidateMessagePopup';
import Confirm from '@/executor/open/reconfirm';
import WorkForm from '@/executor/tools/workForm';
import { model } from '@/ts/base';
import { ReportTaskTreeNodeView } from '@/ts/base/model';
import { IWork, IWorkApply, IWorkTask } from '@/ts/core';
import { Input, Spin, message } from 'antd';
import 'lodash';
import React, { ReactElement, useEffect, useRef, useState } from 'react';
import './default.less';
import WorkFormService from '@/ts/scripting/core/services/WorkFormService';
import { IWorkDarft } from '@/ts/core/work/draft';
import { mapErrorToValidateInfo } from '@/ts/scripting/js/util';

// 卡片渲染
interface IProps {
  apply: IWorkApply;
  work: IWork | IWorkTask | IWorkDarft;
  finished?: (success: boolean, instanceId?: string) => void;
  onStagging?: (instanceId: string) => void;
  staggingId?: string;
  content?: string;
  children?: ReactElement;
  splitDetailFormId?: string;
  curTreeNode?: ReportTaskTreeNodeView;
}

/** 办事发起-默认类型 */
const DefaultWayStart: React.FC<IProps> = ({
  apply,
  work,
  finished,
  content = '',
  splitDetailFormId,
  curTreeNode,
}) => {
  const info: { content: string } = { content };
  const [isModalOpen, setIsModalOpen] = useState(false); //二次确认框
  const [loading, setLoading] = useState(false);
  const [instanceData] = useState<model.InstanceDataModel>();
  const service = useRef(
    new WorkFormService(
      apply.target,
      apply.instanceData,
      true,
      apply.reception,
      apply.assignTask,
    ),
  );
  const saveStatus = useRef<boolean>(false);
  useEffect(() => {
    saveStatus.current = false;

    const ret = service.current.init();
    if (ret instanceof Error) {
      if (Array.isArray(ret.cause)) {
        service.current.handlingResult(
          ret.cause.map((e) => mapErrorToValidateInfo(e, '初始化')),
        );
      } else {
        service.current.handlingResult([mapErrorToValidateInfo(ret, '初始化')]);
      }
    }
  }, []);

  return (
    <div className="workstart-default">
      <div className="workstart-content">
        <div className="workstart-content-right">
          {loading && (
            <div className="loading-spin">
              <Spin spinning></Spin>
            </div>
          )}
          <WorkForm
            allowEdit
            belong={apply.target.space}
            data={apply.instanceData}
            nodeId={apply.instanceData.node.id}
            service={service.current}
            splitDetailFormId={splitDetailFormId}
            instanceData={instanceData}
          />
        </div>
      </div>
      <div className="workstart-content-bottom">
        <FormValidateMessage service={service.current} />
      </div>
      <div className="workstart--toolbar">
        <div className="examineContent">
          <div>备注信息：</div>
          <div className="examineInput">
            <Input
              placeholder="请填写备注信息"
              bordered={false}
              defaultValue={content}
              onChange={(e) => {
                info.content = e.target.value;
              }}
            />
          </div>
        </div>
      </div>
      {isModalOpen && !saveStatus.current && (
        <Confirm
          open={isModalOpen}
          onCancel={() => setIsModalOpen(false)}
          onOk={async () => {
            if (curTreeNode?.directionChildrenComplete === false) {
              message.warn('直属下级节点存在未完结节点！');
              return null;
            }
            if (saveStatus.current) {
              message.warn('请勿重复提交单据！');
              return null;
            }
            saveStatus.current = true;
            setIsModalOpen(false);
            try {
              setLoading(true);
              const instance = await apply.createApply(
                apply.target.spaceId,
                info.content,
                new Map([]),
              );
              if (instance) {
                message.success('提交成功');
                finished?.(true, instance.id);
              } else {
                message.warn('提交失败');
                saveStatus.current = false;
              }
            } finally {
              setLoading(false);
            }
          }}
        />
      )}
    </div>
  );
};

export default DefaultWayStart;
